package com.insigma.business.qrcode.job._bff.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.insigma.business.common.dto.CurrentUser;
import com.insigma.business.common.utils.CurrentUserUtil;
import com.insigma.business.qrcode.common.converter.CompanyProviderConverter;
import com.insigma.business.qrcode.common.converter.JobFairParticipateProviderConverter;
import com.insigma.business.qrcode.common.converter.JobFairProviderConverter;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.template.area.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.util.RpcContextUtil;
import com.insigma.business.qrcode.common.util.SessionUtils;
import com.insigma.business.qrcode.common.vo.*;
import com.insigma.business.qrcode.job._bff.JobFairBFFProvider;
import com.insigma.business.qrcode.job.dto.*;
import com.insigma.business.qrcode.job.dto.request.JobFairInsertRequest;
import com.insigma.business.qrcode.job.dto.request.JobFairParticipateUpdateRequest;
import com.insigma.business.qrcode.job.dto.request.JobFairSearchRequest;
import com.insigma.business.qrcode.job.dto.request.JobFairUpdateRequest;
import com.insigma.business.qrcode.job.dto.search.JobFairBSearcher;
import com.insigma.business.qrcode.job.entity.JobFairDO;
import com.insigma.business.qrcode.job.entity.TrainingMentorDO;
import com.insigma.business.qrcode.job.service.JobFairRecruitPositionService;
import com.insigma.business.qrcode.job.service.JobFairService;
import com.insigma.business.qrcode.job.service.JobFairSignInfoService;
import com.insigma.business.qrcode.soldier.dto.CompanyDTO;
import com.insigma.business.qrcode.soldier.dto.OrgTypeEnum;
import com.insigma.business.qrcode.soldier.dto.SimpleApiRequest;
import com.insigma.business.qrcode.soldier.entity.CompanyDO;
import com.insigma.business.qrcode.soldier.entity.JobFairParticipateDO;
import com.insigma.business.qrcode.soldier.request.BaseGetRequest;
import com.insigma.business.qrcode.soldier.service.CompanyService;
import com.insigma.business.qrcode.soldier.service.JobFairParticipateService;
import com.insigma.business.qrcode.soldier.service.JobRecruitPositionService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class JobFairBFFProviderImpl  extends BaseProviderImpl implements JobFairBFFProvider {
    @Autowired
    private JobFairService jobFairService;

    @Autowired
    private JobFairRecruitPositionService jobFairRecruitPositionService;

    @Autowired
    private JobRecruitPositionService jobRecruitPositionService;

    @Autowired
    private JobFairSignInfoService jobFairSignInfoService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private JobFairParticipateService jobFairParticipateService;

    @Override
    public BasePagingResponse<List<JobFairDTO>> searchJobFair(final JobFairSearchRequest searchRequest) {

        final BasePagingResponse<List<JobFairDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页JobFair的请求参数不能为空");
            }

            @Override
            public void executeService() {
                CurrentUser currentUser = CurrentUserUtil.getCurrentUser();
                if (currentUser != null && !StringUtils.isBlank(currentUser.getWechatOpenid())) {
                    searchRequest.setPublished(true);
                }
                searchRequest.setSortKeyValueJoint("createDatetime_desc");
                PageHelper.startPage(searchRequest.getPageNo(), searchRequest.getPageSize());
                final JobFairBSearcher jobFairBSearcher = JobFairProviderConverter.convertRequestSO2Searcher(searchRequest);
                final List<JobFairDO> jobFairDOList = jobFairService.search(jobFairBSearcher);
                PageInfo<JobFairDO> pageInfo = new PageInfo<>(jobFairDOList);
                for (JobFairDO jobFairDO : jobFairDOList) {
                    /**
                     * 线上/线下招聘会处理逻辑判断
                     * 线上招聘会：根据“招聘会结束时间”字段判断状态。如果小于等于这个时间则表示“进行中”，大于这个时间表示“已结束”
                     * 线下招聘会：根据“举办时间”字段判断状态。如果小于等于这个时间的开始时间，则表示“未开始”。在这个时间范围内表示“进行中”，大于等于这个时间表示“已结束”
                     */
                    if (jobFairDO.getMode().equals(FairModeEnum.ONLINE.name())) {
                        //未开始且结束时间小于等于当前时间，修改为进行中
                        if (FairStatusEnum.NOT_START.name().equals(jobFairDO.getStatus()) && Boolean.TRUE.equals(jobFairDO.getPublished())) {
                            if (!jobFairDO.getHoldBeginDatetime().after(new Date())) {
                                jobFairDO.setStatus(FairStatusEnum.IN_PROGRESS.name());
                                jobFairService.update(jobFairDO);
                            }
                        }
                        //进行中且大于当前时间，修改为已结束
                        if (FairStatusEnum.IN_PROGRESS.name().equals(jobFairDO.getStatus()) && Boolean.TRUE.equals(jobFairDO.getPublished())) {
                            if (jobFairDO.getHoldEndDatetime().before(new Date())) {
                                jobFairDO.setStatus(FairStatusEnum.FINISHED.name());
                                jobFairService.update(jobFairDO);
                            }
                        }
                    } else if (jobFairDO.getMode().equals(FairModeEnum.OFFLINE.name())) {
                        //未开始且当前时间处于举办开始、结束时间范围内，修改为进行中
                        if (FairStatusEnum.NOT_START.name().equals(jobFairDO.getStatus()) && Boolean.TRUE.equals(jobFairDO.getPublished())) {
                            if (!new Date().before(jobFairDO.getHoldBeginDatetime()) && !new Date().after(jobFairDO.getHoldEndDatetime())) {
                                jobFairDO.setStatus(FairStatusEnum.IN_PROGRESS.name());
                                jobFairService.update(jobFairDO);
                            }
                        }
                        //进行中且结束时间大于当前时间，修改为已结束
                        if (FairStatusEnum.IN_PROGRESS.name().equals(jobFairDO.getStatus()) && Boolean.TRUE.equals(jobFairDO.getPublished())) {
                            if (jobFairDO.getHoldEndDatetime().before(new Date())) {
                                jobFairDO.setStatus(FairStatusEnum.FINISHED.name());
                                jobFairService.update(jobFairDO);
                            }
                        }
                    }
                }
                final List<JobFairDTO> jobFairDTOList = JobFairProviderConverter.convertResponseDOList2DTOList(jobFairDOList);
                if (CollectionUtils.isNotEmpty(jobFairDTOList)) {
                    for (JobFairDTO jobFairDO : jobFairDTOList) {
                        int count = jobFairRecruitPositionService.countByFairAndStatus(jobFairDO.getId(), null);
                        jobFairDO.setEnterCompanyCount(count);
                    }
                }
                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, jobFairDTOList, searchRequest, pageInfo.getTotal());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_FAIR_SEARCH;
            }
        });

        return basePagingResponse;
    }



    @Override
    public BaseResponse<JobFairDTO> getJobFair(final BaseGetRequest baseGetRequest){

        final BaseResponse<JobFairDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条JobFair的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String)baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                SessionCompanyUser sessionCompanyUser = RpcContextUtil.getSessionCompanyUser();

                final JobFairDO jobFairDO = jobFairService.get((String) baseGetRequest.getId());
                BizCheckUtil.checkNotNull(jobFairDO, "招聘会不存在");

                final JobFairDTO remoteObj = JobFairProviderConverter.convertResponseDO2DTO(jobFairDO);

                int count = jobFairRecruitPositionService.countByFairAndStatus(remoteObj.getId(), JobCheckStatusEnum.SUCCESS.name());
                remoteObj.setEnterCompanyCount(count);

                int enterPositionCount = jobRecruitPositionService.countByFair(remoteObj.getId());
                remoteObj.setEnterPositionCount(enterPositionCount);

                Integer fairId = jobFairSignInfoService.countByFairId(remoteObj.getId());
                remoteObj.setEnterSoldierCount(fairId);

                if (sessionCompanyUser != null) {
                    BizCheckUtil.checkNotNull(sessionCompanyUser.getUserId(), "获取单条Company的请求参数userId不能为空");
                    final CompanyDO companyDO = companyService.getByUserId(sessionCompanyUser.getUserId());
                    final CompanyDTO companyInfo = CompanyProviderConverter.convertResponseDO2DTO(companyDO);
                    BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "招聘会Id不能为空");
                    BizCheckUtil.checkNotBlank(companyInfo.getId(), "orgType公司Id不能为空");
                    BizCheckUtil.checkNotBlank(OrgTypeEnum.COMPANY.name(), "公司类型不能为空");

                    JobFairParticipateDO jobFairParticipateDO = jobFairParticipateService.getParticipateByFairIdAndOrgId((String) baseGetRequest.getId(),companyInfo.getId(), OrgTypeEnum.COMPANY.name());
                    if (jobFairParticipateDO != null && remoteObj != null) {
                        remoteObj.setApplyStatus(jobFairParticipateDO.getAuditStatus());
                        remoteObj.setJobFairBooth(jobFairParticipateDO.getJobFairBooth());
                    }
                }

                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_FAIR_GET;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<String> insertJobFair(final JobFairInsertRequest insertRequest){

        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增JobFair的请求参数不能为空");
            }
            @Override
            public void executeService() {
                String govUserId = SessionUtils.getGovUserId();
                insertRequest.setCreatorId(govUserId);
                insertRequest.setCreatorType(UserTypeEnum.GOV_EMPLOYEE.name());
                if (Strings.isBlank(insertRequest.getMode())) {
                    insertRequest.setMode(FairModeEnum.OFFLINE.name());
                }
                if (FairModeEnum.ONLINE.name().equals(insertRequest.getMode())) {
                    insertRequest.setHoldBeginDatetime(new Date());
                }
//                BaseResponse<String> jobFairResponse = jobFairConsumer.insertJobFair(insertRequest);
                final JobFairDO jobFairDO = JobFairProviderConverter.convertRequestIO2DO(insertRequest);
                jobFairDO.setStatus(FairStatusEnum.NOT_START.name());
                jobFairDO.setPublished(true);
                jobFairDO.setQr(QrTypeEnum.FAIR_ENTER.getDesc() + UUID.randomUUID().toString());
                jobFairService.insert(jobFairDO);
                ResponseUtils.setupSuccessResponse(baseResponse, jobFairDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_FAIR_INSERT;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> updateJobFair(final JobFairUpdateRequest updateRequest){

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改JobFair的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
            }
            @Override
            public void executeService() {
                updateRequest.setModifierId(SessionUtils.getGovUserId());
                updateRequest.setModifierType(UserTypeEnum.GOV_EMPLOYEE.name());
//                BaseResponse<Integer> jobFairResponse = jobFairConsumer.updateJobFair(updateRequest);
//                BeanUtil.copyProperties(jobFairResponse, baseResponse);
                JobFairDO jobFairDO = JobFairProviderConverter.convertRequestUO2DO(updateRequest);
                Integer affectRowNum = jobFairService.update(jobFairDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_FAIR_UPDATE;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> deleteJobFair(final BaseDeleteRequest deleteRequest){

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除JobFair的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String)deleteRequest.getId(), "id不能为空");
                //BizCheckUtil.checkNotBlank((String)deleteRequest.getModifierId(),"操作人不能为空");
                //BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(),"操作人类型不能为空");
            }
            @Override
            public void executeService() {
                deleteRequest.setModifierType(UserTypeEnum.GOV_EMPLOYEE.name());
                deleteRequest.setModifierId(SessionUtils.getGovUserId());
                deleteRequest.setModifyDatetime(new Date());
//                BaseResponse<Integer> jobFairResponse = jobFairConsumer.deleteJobFair(deleteRequest);
//                BeanUtil.copyProperties(jobFairResponse, baseResponse);
                final Integer affectRowNum = jobFairService.delete((String) deleteRequest.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_FAIR_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> updateBooth(JobFairParticipateUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "修改JobFairParticipate的请求参数不能为空");
        BizCheckUtil.checkNotNull(updateRequest.getJobFairBooth(), "席位不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");

//        return jobFairParticipateConsumer.updateBooth(request);

        updateRequest.setModifierId(SessionUtils.getGovUserId());
        updateRequest.setModifierType(UserTypeEnum.GOV_EMPLOYEE.name());
        BizCheckUtil.checkNotNull(updateRequest, "修改JobFairParticipate的请求参数不能为空");
        BizCheckUtil.checkNotNull(updateRequest.getJobFairBooth(), "席位不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getModifierId(), "操作人不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");

        JobFairParticipateDO pdo = jobFairParticipateService.get(updateRequest.getId());
        BizCheckUtil.checkNotNull(pdo, "还未报名");
        BizCheckUtil.checkIsTrue(pdo.getAuditStatus().equals(JobCheckStatusEnum.SUCCESS.name()), "还未审核通过");
        pdo.setJobFairBooth(updateRequest.getJobFairBooth());
        pdo.setModifierId(updateRequest.getModifierId());
        pdo.setModifierType(updateRequest.getModifierType());
        Integer update = jobFairParticipateService.update(pdo);
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> checkApply(JobFairParticipateUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "修改JobFairParticipate的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getId(), "id不能为空");
        BizCheckUtil.checkNotBlank(request.getAuditStatus(), "审核状态不能为空");
//        JobCheckStatusEnum jobCheckStatusEnum = JobCheckStatusEnum.valueOf(request.getAuditStatus());
//        BizCheckUtil.checkIsTrue(JobCheckStatusEnum.SUCCESS.equals(jobCheckStatusEnum) || JobCheckStatusEnum.REJECT.equals(jobCheckStatusEnum), "状态错误");

//        return jobFairParticipateConsumer.checkApply(request);
        BizCheckUtil.checkNotNull(request, "修改JobFairParticipate的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getId(), "id不能为空");
        BizCheckUtil.checkNotBlank(request.getAuditStatus(), "审核状态不能为空");
        JobCheckStatusEnum jobCheckStatusEnum = JobCheckStatusEnum.valueOf(request.getAuditStatus());
        BizCheckUtil.checkIsTrue(JobCheckStatusEnum.SUCCESS.equals(jobCheckStatusEnum) || JobCheckStatusEnum.REJECT.equals(jobCheckStatusEnum), "状态错误");

        JobFairParticipateDO jobFairParticipateDO = jobFairParticipateService.get(request.getId());
        BizCheckUtil.checkNotNull(jobFairParticipateDO, "不存在");
        jobFairParticipateDO.setAuditStatus(request.getAuditStatus());
        jobFairParticipateDO.setModifierType(request.getModifierType());
        jobFairParticipateDO.setModifierId(request.getModifierId());
        Integer update = jobFairParticipateService.update(jobFairParticipateDO);
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> publishFair(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getId(), "id不能为空");
        BizCheckUtil.checkNotNull(request.getPublished(), "published不能为空");

        request.setModifierId(SessionUtils.getGovUserId());

//        return jobFairConsumer.publishFair(request);
        BizCheckUtil.checkNotNull(request, "请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getId(), "id不能为空");
        BizCheckUtil.checkNotNull(request.getPublished(), "id不能为空");

        JobFairDO jobFairDO = jobFairService.get(request.getId());
        BizCheckUtil.checkNotNull(jobFairDO, "招聘会不存在");
        jobFairDO.setPublished(request.getPublished());

        if (jobFairDO.getMode().equals(FairModeEnum.ONLINE.name())) {
            if (request.getPublished()) {
                jobFairDO.setStatus(FairStatusEnum.IN_PROGRESS.name());
            } else {
                jobFairDO.setStatus(FairStatusEnum.NOT_START.name());
            }
        }

        Integer update = jobFairService.update(jobFairDO);
        return ResponseUtils.buildSuccessResponse(update);
    }
}
